/* eslint-disable @next/next/no-img-element */
import styles from "./search.module.scss";
import { GetServerSideProps } from "next";
import * as React from "react";
import { IArticle, IUser } from "../../types";
import * as userService from "../../services/user.service";
import { Button, Select, Menu, Dropdown, Input } from "antd";
import "antd/dist/antd.css";
import { useRouter } from "next/router";
import toast from "../../components/Toast";
import * as articleService from "../../services/article.service";
import ArticleItem from "../../components/articleItem";
import IconFont from "../../assets/icon";
import Link from "next/link";

const { Option } = Select;

interface Props {
  user: IUser;
  articles: IArticle[];
  content: string;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const result = await userService.userInfo(ctx.req.cookies.token);
  const res = await articleService.search(ctx.query.id as string);
  res.rows.sort((a: IArticle, b: IArticle) => {
    return new Date(b.time).valueOf() - new Date(a.time).valueOf();
  });
  if (result.stat === "OK") {
    return {
      props: {
        user: result.data,
        articles: res.rows,
        content: ctx.query.id,
      },
    };
  } else {
    return {
      props: {
        user: null,
        articles: res.rows,
        content: ctx.query.id,
      },
    };
  }
};

const menu = (
  <Menu>
    <Menu.Item>
      <Link href="/me" passHref>
        个人主页
      </Link>
    </Menu.Item>
    <Menu.Item>
      <Link href="/login" passHref>
        切换账号
      </Link>
    </Menu.Item>
  </Menu>
);

export default function Home(props: Props) {
  const [content, setContent] = React.useState<string>("");
  const [rows, setRows] = React.useState<IArticle[]>(props.articles);

  const router = useRouter();

  const submit = async () => {
    if (content === "") {
      toast("请输入内容");
    } else {
      const res = await articleService.search(content);
      router.push("/search/" + content);
      setRows(res.rows);
    }
  };

  function handleChange(value: string) {
    switch (value) {
      case "按时间":
        const newrows = rows.sort((a: IArticle, b: IArticle) => {
          return new Date(b.time).valueOf() - new Date(a.time).valueOf();
        });
        setRows([...newrows]);
        return;
      case "按浏览量":
        const newrows2 = rows.sort((a: IArticle, b: IArticle) => {
          return b.views - a.views;
        });
        setRows([...newrows2]);
        return;
      case "按热度":
        const newrows3 = rows.sort((a: IArticle, b: IArticle) => {
          return b.likes - a.likes;
        });
        setRows([...newrows3]);
    }
  }

  const postArticle = async () => {
    if (props.user === null) {
      toast("请登录");
      router.push("/login");
    } else {
      router.push("/post");
    }
  };

  return (
    <>
      <div className={styles.header}>
        <Link href={"/"} passHref>
          <div className={styles.logo}>懂乎</div>
        </Link>

        <div className={styles.search}>
          <Input
            className={styles.input}
            placeholder="请输入要搜索的内容"
            allowClear
            width="50px"
            onChange={(e) => {
              setContent(e.target.value);
            }}
            suffix={
              <IconFont
                onClick={submit}
                className={styles.iconsearch}
                type="icon-sousuo"
              />
            }
          />
        </div>
        <Dropdown
          overlay={menu}
          placement="bottomCenter"
          arrow
          className={props.user ? "" : styles.none}
        >
          <IconFont type="icon-chilun--" className={styles.icon} />
        </Dropdown>
        <div className={styles.right}>
          <Button
            onClick={() => router.push("/login")}
            className={props.user ? styles.none : styles.login}
          >
            登录/注册
          </Button>
          <div className={props.user ? styles.user : styles.none}>
            <span className={styles.username}>{props.user?.nickname}</span>
            <div
              style={{
                backgroundImage: `url(/api/article/download/${props.user?.avatar})`,
                height: "30px",
                width: "30px",
                borderRadius: "30px",
                backgroundSize: "cover",
              }}
            ></div>
          </div>
        </div>
      </div>

      <div className={styles.back}>
        <div className={styles.main}>
          <div className={styles.nav}>
            <div className={styles.text}>以下为“{props.content}”的搜索结果</div>
            <Select
              className={styles.select}
              defaultValue="按时间"
              style={{ width: 120 }}
              onChange={handleChange}
            >
              <Option value="按时间">按时间</Option>
              <Option value="按浏览量">按浏览量</Option>
              <Option value="按热度">按热度</Option>
            </Select>
            <Button className={styles.post} size="large" onClick={postArticle}>
              发布文章
            </Button>
          </div>
          <div className={styles.articles}>
            {rows.map((item, index) => {
              return <ArticleItem key={index} item={item} />;
            })}
          </div>
        </div>
      </div>
    </>
  );
}
